import requests
import os
import subprocess

# 定义生成音频的API和下载音频的API地址
generate_audio_url = 'http://10.31.0.6:5002/generate_audio'
download_audio_url = 'http://10.31.0.6:5002/'

# 定义关键词列表
keywords = ['善行']

# 定义headers
headers = {
    'Accept': '*/*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'http://10.31.0.6:5002',
    'Referer': 'http://10.31.0.6:5002/',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
}

# 裁剪音频函数
def trim_audio(input_file, output_file, start_time):
    # 使用ffmpeg裁剪音频，去除开头的空白部分
    command = [
        'ffmpeg',
        '-i', input_file,  # 输入文件
        '-ss', start_time,  # 裁剪的起始时间
        '-c', 'copy',  # 使用复制模式，保留原格式
        output_file
    ]
    subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# 遍历关键词列表，生成音频并下载
for keyword in keywords:
    # 第一步：调用生成音频的API
    data = {
        'text': keyword,
        'model_id': '4d18729af294470b9d59d85ba6bbb682',  # 请根据需要修改
        'speed': '1',
        'volume': '0'
    }
    response = requests.post(generate_audio_url, headers=headers, data=data, verify=False)
    
    if response.status_code == 200:
        # 第二步：从返回的响应中提取音频文件路径
        audio_file = response.json().get('audio_file')  # 提取音频文件路径
        if audio_file:
            # 构建下载音频的完整URL
            download_url = download_audio_url + audio_file.strip('/')

            # 第三步：下载音频文件
            audio_response = requests.get(download_url, headers=headers, verify=False)
            if audio_response.status_code == 200:
                # 保存音频文件
                original_audio_path = f"{keyword}_original.mp3"
                with open(original_audio_path, 'wb') as f:
                    f.write(audio_response.content)
                print(f"音频 '{keyword}_original.mp3' 已保存")

                # 裁剪音频文件，去除开头空白部分
                trimmed_audio_path = f"{keyword}_trimmed.mp3"
                trim_audio(original_audio_path, trimmed_audio_path, '0.1')  # 裁剪前0.1秒
                print(f"音频 '{keyword}_trimmed.mp3' 已裁剪并保存")
                
            else:
                print(f"下载音频失败: {download_url}")
        else:
            print(f"未能从生成音频响应中提取音频文件路径")
    else:
        print(f"生成音频失败: {keyword}")
